import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/providers/vocabulary_learning_provider.dart';
import '../../shared/providers/word_provider.dart';
import '../../data/master_vocabulary.dart';
import '../words/favorites_page.dart';

class VocabularyLearningPage extends ConsumerStatefulWidget {
  final String? category;
  final int? difficulty;
  final int? questionCount;

  const VocabularyLearningPage({
    super.key,
    this.category,
    this.difficulty,
    this.questionCount,
  });

  @override
  ConsumerState<VocabularyLearningPage> createState() => _VocabularyLearningPageState();
}

class _VocabularyLearningPageState extends ConsumerState<VocabularyLearningPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  
  // 动画控制器
  late AnimationController _cardAnimationController;
  late AnimationController _progressAnimationController;
  late Animation<double> _cardAnimation;
  late Animation<double> _progressAnimation;
  
  Timer? _autoNextTimer;
  int? _selectedAnswer;
  bool _showResult = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 初始化动画控制器
    _cardAnimationController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    
    _progressAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _cardAnimation = CurvedAnimation(
      parent: _cardAnimationController,
      curve: Curves.easeInOutBack,
    );
    
    _progressAnimation = CurvedAnimation(
      parent: _progressAnimationController,
      curve: Curves.easeOutCubic,
    );
    
    // 启动初始动画
    _cardAnimationController.forward();
    _progressAnimationController.forward();
    
    // 初始化学习会话
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 如果指定了类别，使用该类别的所有单词数量
      int questionCount = widget.questionCount ?? 20;
      if (widget.category != null) {
        final categoryWords = MasterVocabulary.getWordsByCategory(widget.category!);
        questionCount = categoryWords.length; // 使用类别中的所有单词
      }
      
      await ref.read(vocabularyLearningProvider.notifier).initializeLearning(
        category: widget.category,
        difficulty: widget.difficulty,
        questionCount: questionCount,
      );
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _cardAnimationController.dispose();
    _progressAnimationController.dispose();
    _autoNextTimer?.cancel();
    super.dispose();
  }

  void _onAnswerSelected(int index) {
    if (_selectedAnswer != null) return;

    setState(() {
      _selectedAnswer = index;
      _showResult = true;
    });

    ref.read(vocabularyLearningProvider.notifier).answerQuestion(index);

    // 1.5秒后自动跳转下一题
    _autoNextTimer = Timer(const Duration(milliseconds: 1500), () {
      _nextQuestion();
    });
  }

  void _nextQuestion() {
    _autoNextTimer?.cancel();
    
    final learningState = ref.read(vocabularyLearningProvider);
    if (learningState.hasNext) {
      _cardAnimationController.reverse().then((_) async {
        await ref.read(vocabularyLearningProvider.notifier).nextQuestion();
        setState(() {
          _selectedAnswer = null;
          _showResult = false;
        });
        _cardAnimationController.forward();
        _progressAnimationController.forward();
      });
    } else {
      // 完成学习
      ref.read(vocabularyLearningProvider.notifier).nextQuestion();
    }
  }

  void _restartLearning() async {
    await ref.read(vocabularyLearningProvider.notifier).restartLearning();
    
    // 如果指定了类别，使用该类别的所有单词数量
    int questionCount = widget.questionCount ?? 20;
    if (widget.category != null) {
      final categoryWords = MasterVocabulary.getWordsByCategory(widget.category!);
      questionCount = categoryWords.length; // 使用类别中的所有单词
    }
    
    await ref.read(vocabularyLearningProvider.notifier).initializeLearning(
      category: widget.category,
      difficulty: widget.difficulty,
      questionCount: questionCount,
    );
    setState(() {
      _selectedAnswer = null;
      _showResult = false;
    });
    _cardAnimationController.forward();
    _progressAnimationController.reset();
    _progressAnimationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    final learningState = ref.watch(vocabularyLearningProvider);
    final favoriteWords = ref.watch(favoriteWordsProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Vocabulary Learning'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: AppConstants.PRIMARY_BLUE,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                AppConstants.PRIMARY_BLUE,
                AppConstants.DARK_BLUE,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        actions: learningState.questions.isNotEmpty && !learningState.isCompleted ? [
          if (learningState.currentQuestion != null && !learningState.isCompleted)
            Container(
              margin: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Stack(
                children: [
                  IconButton(
                    onPressed: () {
                      ref.read(favoriteWordsProvider.notifier)
                          .toggleFavorite(learningState.currentQuestion!.correctWord.id);
                      ref.read(starredRefreshProvider.notifier).state++;
                    },
                    icon: FaIcon(
                      favoriteWords.contains(learningState.currentQuestion?.correctWord.id)
                          ? FontAwesomeIcons.solidStar
                          : FontAwesomeIcons.star,
                      color: favoriteWords.contains(learningState.currentQuestion?.correctWord.id)
                          ? Colors.amber
                          : Colors.white70,
                      size: 18,
                    ),
                  ),
                ],
              ),
            ),
        ] : null,
      ),
      body: learningState.questions.isEmpty
          ? const Center(child: CircularProgressIndicator())
          : learningState.isCompleted
              ? _buildCompletionScreen()
              : _buildLearningContent(),
    );
  }

  Widget _buildLearningContent() {
    final learningState = ref.watch(vocabularyLearningProvider);
    final question = learningState.currentQuestion!;

    return Column(
      children: [
        _buildProgressBar(),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                _buildQuestionCard(question),
                const SizedBox(height: 40),
                _buildOptionsGrid(question),
                const SizedBox(height: 20),
                _buildBottomInfo(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildProgressBar() {
    final learningState = ref.watch(vocabularyLearningProvider);
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${learningState.currentQuestionIndex + 1} / ${learningState.questions.length}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
              Text(
                'Accuracy: ${(learningState.accuracy * 100).toInt()}%',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppConstants.PRIMARY_BLUE,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              return LinearProgressIndicator(
                value: learningState.progress * _progressAnimation.value,
                backgroundColor: Colors.grey[300],
                valueColor: AlwaysStoppedAnimation<Color>(AppConstants.PRIMARY_BLUE),
                minHeight: 6,
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionCard(VocabularyQuestion question) {
    return AnimatedBuilder(
      animation: _cardAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _cardAnimation.value,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.all(30),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  AppConstants.PRIMARY_BLUE.withOpacity(0.9),
                  AppConstants.DARK_BLUE,
                ],
              ),
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.3),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              children: [
                const FaIcon(
                  FontAwesomeIcons.language,
                  color: Colors.white,
                  size: 32,
                ),
                const SizedBox(height: 20),
                Text(
                  question.correctWord.esperanto,
                  style: const TextStyle(
                    fontSize: 36,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    letterSpacing: 1.2,
                  ),
                ),
                const SizedBox(height: 12),
                Text(
                  '[${question.correctWord.pronunciation}]',
                  style: const TextStyle(
                    fontSize: 18,
                    color: Colors.white70,
                    fontStyle: FontStyle.italic,
                  ),
                ),
                const SizedBox(height: 20),
                const Text(
                  'Choose the correct English translation:',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildOptionsGrid(VocabularyQuestion question) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 2.5,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
      ),
      itemCount: question.options.length,
      itemBuilder: (context, index) {
        return _buildOptionButton(question, index);
      },
    );
  }

  Widget _buildOptionButton(VocabularyQuestion question, int index) {
    final option = question.options[index];
    final isSelected = _selectedAnswer == index;
    final isCorrect = index == question.correctIndex;
    
    Color backgroundColor = Colors.white;
    Color borderColor = Colors.grey.withOpacity(0.3);
    Color textColor = AppConstants.DARK_BLUE;
    
    if (_showResult && isSelected) {
      if (isCorrect) {
        backgroundColor = Colors.green.withOpacity(0.1);
        borderColor = Colors.green;
        textColor = Colors.green.shade700;
      } else {
        backgroundColor = Colors.red.withOpacity(0.1);
        borderColor = Colors.red;
        textColor = Colors.red.shade700;
      }
    } else if (_showResult && isCorrect) {
      backgroundColor = Colors.green.withOpacity(0.1);
      borderColor = Colors.green;
      textColor = Colors.green.shade700;
    }

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: Material(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(16),
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: _selectedAnswer == null ? () => _onAnswerSelected(index) : null,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: borderColor, width: 2),
            ),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (_showResult && isSelected) ...[
                    FaIcon(
                      isCorrect ? FontAwesomeIcons.check : FontAwesomeIcons.xmark,
                      color: isCorrect ? Colors.green : Colors.red,
                      size: 16,
                    ),
                    const SizedBox(width: 8),
                  ],
                  Flexible(
                    child: Text(
                      option,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: textColor,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomInfo() {
    final learningState = ref.watch(vocabularyLearningProvider);
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            icon: FontAwesomeIcons.bullseye,
            label: 'Correct',
            value: '${learningState.totalCorrect}',
            color: Colors.green,
          ),
          _buildStatItem(
            icon: FontAwesomeIcons.star,
            label: 'Mastered',
            value: '${learningState.masteredWords.length}',
            color: Colors.orange,
          ),
          _buildStatItem(
            icon: FontAwesomeIcons.chartLine,
            label: 'Progress',
            value: '${(learningState.progress * 100).toInt()}%',
            color: AppConstants.PRIMARY_BLUE,
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Column(
      children: [
        FaIcon(icon, color: color, size: 20),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildCompletionScreen() {
    final stats = ref.read(vocabularyLearningProvider.notifier).getLearningStats();
    
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [AppConstants.PRIMARY_BLUE, AppConstants.DARK_BLUE],
                ),
                shape: BoxShape.circle,
              ),
              child: const Center(
                child: FaIcon(
                  FontAwesomeIcons.trophy,
                  color: Colors.white,
                  size: 50,
                ),
              ),
            ),
            const SizedBox(height: 32),
            const Text(
              'Congratulations!',
              style: TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: AppConstants.DARK_BLUE,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              'You completed the vocabulary session!',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            _buildResultStats(stats),
            const SizedBox(height: 32),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _restartLearning,
                    icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 16),
                    label: const Text('Practice Again'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppConstants.PRIMARY_BLUE,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => Navigator.pop(context),
                    icon: const FaIcon(FontAwesomeIcons.house, size: 16),
                    label: const Text('Back Home'),
                    style: OutlinedButton.styleFrom(
                      foregroundColor: AppConstants.PRIMARY_BLUE,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildResultStats(Map<String, dynamic> stats) {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatCard(
                'Questions',
                '${stats['totalQuestions']}',
                FontAwesomeIcons.listCheck,
                Colors.blue,
              ),
              _buildStatCard(
                'Correct',
                '${stats['correctAnswers']}',
                FontAwesomeIcons.circleCheck,
                Colors.green,
              ),
              _buildStatCard(
                'Accuracy',
                '${(stats['accuracy'] * 100).toInt()}%',
                FontAwesomeIcons.bullseye,
                Colors.orange,
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatCard(
                'Mastered',
                '${stats['masteredWords']}',
                FontAwesomeIcons.star,
                Colors.purple,
              ),
              _buildStatCard(
                'Duration',
                '${stats['duration'].inMinutes}:${(stats['duration'].inSeconds % 60).toString().padLeft(2, '0')}',
                FontAwesomeIcons.clock,
                Colors.indigo,
              ),
              _buildStatCard(
                'Speed',
                '${stats['questionsPerMinute'].toStringAsFixed(1)}/min',
                FontAwesomeIcons.tachometerAlt,
                Colors.red,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String label, String value, IconData icon, Color color) {
    return Column(
      children: [
        FaIcon(icon, color: color, size: 24),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }
} 